package com.gblw.rjkf.pj.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gblw.rjkf.pj.entity.SysDict;
import com.gblw.rjkf.pj.mapper.SysDictMapper;
import com.gblw.rjkf.pj.service.SysDictService;
import com.gblw.rjkf.pj.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * SysDictServiceImpl(SysDict)
 *
 * @author wj
 * @since 2024-09-16 17:36:43
 */
@Slf4j
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService {
    @Resource
    private SysDictMapper sysDictMapper;

    @Override
    public Result page(Integer pageNum, Integer pageSize, String name, String code) {

        QueryWrapper<SysDict> queryWrapper = new QueryWrapper<>();
        // 判断 user_name 是否有值，如果有值则添加到查询条件中
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.eq("name", name);
        }
        // 判断 nick_name 是否有值，如果有值则添加到查询条件中
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.eq("nick_name", code);
        }
        Page<SysDict> page = new Page<>(pageNum, pageSize);
        IPage<SysDict> pageList = sysDictMapper.selectPage(page, queryWrapper);
        return Result.success("查询成功", pageList);
    }

    @Override
    public Result insert(SysDict sysDict) {
        QueryWrapper<SysDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.or(orWrapper -> {
            orWrapper.eq("name", sysDict.getName()).or().eq("code", sysDict.getCode());
        });
        List<SysDict> list = baseMapper.selectList(queryWrapper);
        if (!list.isEmpty()) {
            return Result.error("字典已存在，请检查");
        } else {
            // 插入新记录
            baseMapper.insert(sysDict);
            return Result.success("添加成功", "");
        }
    }

    @Override
    public Result update(SysDict sysDict) {

        // 获取当前要更新的记录的 ID
        Integer currentId = sysDict.getId();

        // 创建查询包装器
        QueryWrapper<SysDict> queryWrapper = new QueryWrapper<>();

        // 构建 OR 条件：name 或 code 任意一个存在，并且排除当前记录的 ID
        queryWrapper.or(orWrapper -> {
            orWrapper.eq("name", sysDict.getName());
            orWrapper.eq("code", sysDict.getCode());
        }).ne(currentId != null, "id", currentId);

        // 执行查询
        List<SysDict> list = baseMapper.selectList(queryWrapper);

        // 检查是否存在
        if (!list.isEmpty()) {
            return Result.error("字典已存在，请检查");
        } else {
            // 更新记录
            baseMapper.updateById(sysDict);
            return Result.success("更新成功", "");
        }
    }
}
